package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 体温监测-看护日记
 * Created by gaoge on 2017/2/22.
 */
public class TemperatureDiaryActivity extends BaseActivity implements View.OnClickListener {

    //返回键
    private ImageView img_back = null;
    //标题
    private TextView title_name = null;
    //数据显示
    private ListView listview = null;
    //发烧看护
    private TextView fever_care = null;
    //蹬被看护
    private TextView sleep_care = null;
    //洗澡看护
    private TextView bath_care = null;
    //listview适配器
    private ListViewAdapter adapter = null;
    //保存数据的集合
    private ArrayList<HashMap<String, String>> list = new ArrayList<>();
    //记录当前点击状态
    private int click = 0;
    //数据库
    private DBManager db = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.temperature_diary_activity);
        //初始化
        init();
    }

    //初始化
    private void init() {
        db = new DBManager(this);
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title_name = (TextView) findViewById(R.id.title_name);
        fever_care = (TextView) findViewById(R.id.fever_care);
        sleep_care = (TextView) findViewById(R.id.sleep_care);
        bath_care = (TextView) findViewById(R.id.bath_care);
        listview = (ListView) findViewById(R.id.listview);
        //设置标题
        title_name.setText("看护日记");
        //填充数据
        adapter = new ListViewAdapter(this, list);
        listview.setAdapter(adapter);
        //获取数据
        getData();
        //初始化按钮
        setClickColor();
        //设置点击事件
        fever_care.setOnClickListener(this);
        sleep_care.setOnClickListener(this);
        bath_care.setOnClickListener(this);
        //列表点击事件
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String time[]=list.get(position).get("StartTime").split(" ")[0].split("-");
                Intent intent=new Intent(TemperatureDiaryActivity.this, TemperatureSeeCurveActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("careType", Integer.parseInt(list.get(position).get("Type")));
                intent.putExtra("time", time[1]+"月"+time[2]+"日");
                intent.putExtra("state", true);
                intent.putExtra("data", list.get(position).get("data") + "℃");
                intent.putExtra("startTime", list.get(position).get("StartTime"));
                intent.putExtra("continuousTime", list.get(position).get("TotalTime"));
                intent.putExtra("temperatureData", list.get(position).get("MonitoringData"));
                intent.putExtra("timeData", list.get(position).get("MonitoringDataTime"));
                startActivity(intent);
            }
        });
        //listview 长按删除事件
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                deleteDialog(position);
                return true;
            }
        });
    }

    //加载框
    MyAlertDialog dialog;

    /**
     * 胎心监测怀孕状态判断
     */
    private void deleteDialog(final int position) {
        try {
            //加载弹出框
            final MyAlertDialog dialog = new MyAlertDialog();
            dialog.PregnancyStatus_Dialog(this, R.layout.pregnancystatus_dialog);
            //设置内容
            TextView data = dialog.getData();
            data.setText("删除后，本条监测数据将无法恢复，您确定要删除吗？");
            //设置取消按钮
            TextView getCancel_text = dialog.getCancel_text();
            getCancel_text.setText("取消");
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismissOut();
                }
            });
            //设置确认按钮
            TextView getConfirm_text = dialog.getConfirm_text();
            getConfirm_text.setText("确定");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismissOut();
                    db.deleteTemperatrueItem(list.get(position).get("_id"));
                    list.remove(position);
                    adapter.RefreshList(list);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据
    public void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                list = db.selectTemperatrueAll(click);
                mHandler.sendEmptyMessage(1);
            }
        }).start();
    }

    //显示数据
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    adapter.RefreshList(list);
                    break;
            }
        }
    };

    //单击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //发烧看护
            case R.id.fever_care:
                click = 0;
                break;
            //蹬被看护
            case R.id.sleep_care:
                click = 1;
                break;
            //洗澡看护
            case R.id.bath_care:
                click = 2;
                break;
        }
        getData();
        //改变按钮颜色
        setClickColor();
    }

    //设置点击状态
    private void setClickColor() {
        if (click == 0) {
            fever_care.setBackgroundResource(R.drawable.red_left);
            fever_care.setTextColor(this.getResources().getColor(R.color.white));
            sleep_care.setBackgroundResource(R.color.white);
            sleep_care.setTextColor(this.getResources().getColor(R.color.sys_fen));
            bath_care.setBackgroundResource(R.drawable.gray_right);
            bath_care.setTextColor(this.getResources().getColor(R.color.sys_fen));
        } else if (click == 1) {
            fever_care.setBackgroundResource(R.drawable.gray_left);
            fever_care.setTextColor(this.getResources().getColor(R.color.sys_fen));
            sleep_care.setBackgroundResource(R.color.sys_fen);
            sleep_care.setTextColor(this.getResources().getColor(R.color.white));
            bath_care.setBackgroundResource(R.drawable.gray_right);
            bath_care.setTextColor(this.getResources().getColor(R.color.sys_fen));
        } else if (click == 2) {
            fever_care.setBackgroundResource(R.drawable.gray_left);
            fever_care.setTextColor(this.getResources().getColor(R.color.sys_fen));
            sleep_care.setBackgroundResource(R.color.white);
            sleep_care.setTextColor(this.getResources().getColor(R.color.sys_fen));
            bath_care.setBackgroundResource(R.drawable.red_right);
            bath_care.setTextColor(this.getResources().getColor(R.color.white));
        }
    }

    /**
     * 分类列表适配器
     */
    class ListViewAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();

        public ListViewAdapter(Context context,
                               ArrayList<HashMap<String, String>> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        //刷新数据
        public void RefreshList(ArrayList<HashMap<String, String>> getData) {
            this.getData = getData;
            notifyDataSetChanged();
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.temperature_diary_item, null);
                viewHolder.relativeLayout = (RelativeLayout) convertView.findViewById(R.id.relativeLayout);
                viewHolder.date_textview = (TextView) convertView.findViewById(R.id.date_textview);
                viewHolder.temperature = (TextView) convertView.findViewById(R.id.temperature);
                viewHolder.duration = (TextView) convertView.findViewById(R.id.duration);
                viewHolder.normal = (TextView) convertView.findViewById(R.id.normal);
                viewHolder.measure = (TextView) convertView.findViewById(R.id.measure);
                viewHolder.remarks = (TextView) convertView.findViewById(R.id.remarks);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            /**设置边框背景颜色*/
            if (position % 2 == 1) {
                //奇数
                viewHolder.relativeLayout.setBackgroundResource(R.color.bj_color);
            } else {
                //偶数
                viewHolder.relativeLayout.setBackgroundResource(R.color.white);
            }
            /**设置日期*/
            String showTile = getData.get(position).get("listShowTime");
            if (showTile != null && !showTile.equals("") && !showTile.equals("null")) {
                showTile = showTile.split(" ")[0];
                String s = showTile.substring(4, 5);
                long M = Long.parseLong(showTile.split(s)[1]);
                long d = Long.parseLong(showTile.split(s)[2]);
                viewHolder.date_textview.setText(d + "\n" + M + "月");
                viewHolder.date_textview.setBackgroundResource(R.color.sys_fen);
            } else {
                viewHolder.date_textview.setText("");
                viewHolder.date_textview.setBackgroundResource(R.color.white);
            }
            /**设置温度*/
            viewHolder.temperature.setText(getData.get(position).get("data") + "℃");
            /**设置持续时间*/
            viewHolder.duration.setText(getData.get(position).get("time"));
            /**设置标签*/
            if (click == 0) {
                //如果是发烧看护，就设置标签
                String measure = getData.get(position).get("Method");
                String remarks = getData.get(position).get("Note");
                if (Float.parseFloat(getData.get(position).get("data")) > Float.parseFloat(db.selectTemperature("FeverWarning"))) {
                    //如果发烧状态不为空
                    viewHolder.normal.setText("偏高");
                    viewHolder.normal.setVisibility(TextView.VISIBLE);
                } else {
                    if (viewHolder.normal.getVisibility() == View.VISIBLE) {
                        viewHolder.normal.setVisibility(TextView.GONE);
                    }
                }
                if (measure != null && !measure.equals("") && !measure.equals("null")) {
                    //如果措施状态不为空
                    viewHolder.measure.setText(measure);
                    viewHolder.measure.setVisibility(TextView.VISIBLE);
                } else {
                    if (viewHolder.measure.getVisibility() == View.VISIBLE) {
                        viewHolder.measure.setVisibility(TextView.GONE);
                    }
                }
                if (remarks != null && !remarks.equals("") && !remarks.equals("null")) {
                    //如果备注状态不为空
                    viewHolder.remarks.setText(remarks);
                    viewHolder.remarks.setVisibility(TextView.VISIBLE);
                } else {
                    if (viewHolder.remarks.getVisibility() == View.VISIBLE) {
                        viewHolder.remarks.setVisibility(TextView.GONE);
                    }
                }
            } else {
                //如果不是发烧状态，就隐藏标签
                if (viewHolder.normal.getVisibility() == View.VISIBLE) {
                    viewHolder.normal.setVisibility(View.GONE);
                }
                if (viewHolder.measure.getVisibility() == View.VISIBLE) {
                    viewHolder.measure.setVisibility(View.GONE);
                }
                if (viewHolder.remarks.getVisibility() == View.VISIBLE) {
                    viewHolder.remarks.setVisibility(View.GONE);
                }
            }
            return convertView;
        }
    }

    /**
     * 包装类
     */
    private static class ViewHolder {
        private RelativeLayout relativeLayout = null;
        private TextView date_textview = null;
        private TextView temperature = null;
        private TextView duration = null;
        private TextView normal = null;
        private TextView measure = null;
        private TextView remarks = null;
    }
}
